package com.feizhoutuobang.shapeline.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.feizhoutuobang.shapeline.bo.Article;
import com.feizhoutuobang.shapeline.bo.Feed;
import com.feizhoutuobang.shapeline.dao.ArticleDao;
import com.feizhoutuobang.shapeline.util.Calendar;

public class ArticleDaoImpl extends HibernateDaoSupport implements ArticleDao {

	@Override
	public Article getArticleByFeedAndUrl(Feed feed, String link) {
		String hql = "from Article where feed.id=:feed and link=:link";
		Query query = getSession().createQuery(hql);
		query.setString("feed", feed.getId());
		query.setString("link", link);
		return (Article)query.uniqueResult();
	}

	@Override
	public void saveArticle(Article article) {
		getHibernateTemplate().save("Article", article);
	}

	@Override
	public long getArticleCount(Feed feed, Date beginTime, Date endTime) {
		String hql = "select count(*) from Article where feed.id=:feed ";
		if (beginTime != null) {
			hql += "and publishTime>=:beginTime ";
		}
		if (endTime != null) {
			hql += "and publishTime<=:endTime ";
		}
		
		Query query = getSession().createQuery(hql).setString("feed", feed.getId());
		if (beginTime != null) {
			query.setString("beginTime", Calendar.format(beginTime));
		}
		if (endTime != null) {
			query.setString("endTime", Calendar.format(endTime));
		}
		
		return (Long)query.uniqueResult();
	}

	@Override
	public Article getEarlestArticle(Feed feed, Date beginTime, Date endTime) {
		String hql = "from Article where feed.id=:feed ";
		if (beginTime != null) {
			hql += "and publishTime>=:beginTime ";
		}
		if (endTime != null) {
			hql += "and publishTime<=:endTime ";
		}
		hql += "order by publishTime";
		
		Query query = getSession().createQuery(hql).setString("feed", feed.getId());
		if (beginTime != null) {
			query.setString("beginTime", Calendar.format(beginTime));
		}
		if (endTime != null) {
			query.setString("endTime", Calendar.format(endTime));
		}
		query.setFirstResult(0);
		query.setMaxResults(1);

		return (Article)query.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Article> getNewArticleOfFeed(Feed feed, Date lastPublishTime, int maxItemCount) {
		String hql = "from Article where feed.id=:feedId and publishTime_>:lastPublishTime order by publishTime_ desc";
		Query query = getSession().createQuery(hql);
		query.setString("feedId", feed.getId());
		query.setString("lastPublishTime", Calendar.format(lastPublishTime));
		query.setFirstResult(0);
		query.setMaxResults(maxItemCount);
		
		return query.list();
	}

}
